package cn.com.byte1024.controller;

import cn.com.byte1024.entity.User;
import cn.com.byte1024.entity.VoteProject;
import cn.com.byte1024.service.UserService;
import cn.com.byte1024.service.VoteProjectService;
import cn.com.byte1024.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;

/**
 * @ProjectName: VoteSystem
 * @ClassName: UserController
 * @Description:
 * @Author: Kwnda
 * @Date: 2021/1/3 22:31
 */
@Controller
@RequestMapping("/user")
public class UserController{

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private VoteProjectService voteProjectService;

    @RequestMapping("/login")
    public String login(String loginName, String password, HttpServletRequest request, Model model){
        
        //通过登录名查询redis里面的value值跟用户输入的密码相比较一致则返回首页
        if(password.equals(redisUtil.get(loginName))){
            request.getSession().setAttribute("userName",redisUtil.get(loginName+"UserName"));
            request.getSession().setAttribute("loginName", loginName);
            request.getSession().setAttribute("userId",redisUtil.get(loginName+"UserId"));

            List<VoteProject> voteProjectList=voteProjectService.selectAllVoteProject(redisUtil.get(loginName+"UserId").toString());
            if(voteProjectList!=null){
                model.addAttribute("voteProjectList",voteProjectList);
            }
            return "index";
        }
        //不一样则查询数据库
        User user = new User();
        user.setLoginName(loginName);
        user.setPassword(password);
        
        User result = userService.selectByUser(user);
        if(result!=null){
            List<VoteProject> voteProjectList=voteProjectService.selectAllVoteProject(result.getUserId());
            if(voteProjectList!=null){
                model.addAttribute("voteProjectList",voteProjectList);
            }
            request.getSession().setAttribute("userName", result.getUserName());
            request.getSession().setAttribute("loginName", result.getLoginName());
            request.getSession().setAttribute("userId", result.getUserId());
           
            //查询出来的用户的账号密码放入redis，60分钟内免查询数据库
            redisUtil.set(result.getLoginName(),result.getPassword(),(long)60*60);
            redisUtil.set(result.getLoginName()+"UserName", result.getUserName(),(long)60*60);
            redisUtil.set(result.getLoginName()+"UserId", result.getUserId(),(long)60*60);
            return "index";
        }
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "login";
    }
}
